package shopping.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;
import shopping.domain.Product;
import shopping.service.ProductService;
import shopping.utils.RRHolder;
import shopping.utils.UUIDUtil;
import shopping.utils.UploadUtil;
import shopping.web.vo.ResultVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@WebServlet(urlPatterns = "/productadd")
public class ProductAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String[]> parameterMap = UploadUtil.parseRequest(request);

        Product product = new Product();
        try {
            BeanUtils.populate(product,parameterMap);
        } catch (Exception e) {
        }

        product.setPdate(new Date());
        product.setPid(UUIDUtil.getId());
        product.setPflag(1);

        //调用service保存
        new ProductService().save(product);

        ResultVo vo = new ResultVo(ResultVo.CODE_SUCCESS,"");
        String s = new ObjectMapper().writeValueAsString(vo);
        RRHolder.getResponse().getWriter().write(s);
    }
}
